package com.mx.web.base.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

import com.mx.web.model.Pagination;

public class BaseDao<T> {

	protected int PAGE_SIZE = 3;

	@Autowired protected MongoTemplate mongoTemplate;
	
	public BaseDao() {}
	
	/**
	 * 通过条件查询,查询分页结果
	 */
	public Pagination<T> getPage(int currentPage, Query query) {
		long totalCount = this.mongoTemplate.count(query, this.getEntityClass());	//获取总条数
		int totalPage = (int) (totalCount / PAGE_SIZE);						//总页数

		Pagination<T> page = new Pagination<T>(currentPage, totalPage, (int) totalCount);
		
		int skip = (currentPage - 1) * PAGE_SIZE;
		query.skip(skip);			//skip相当于从那条记录开始
		query.limit(PAGE_SIZE);		//从skip开始,取多少条记录

		List<?> items = this.mongoTemplate.find(query, this.getEntityClass());

		return page.build(items);			//获取数据
	}
	
	public Class<?> getEntityClass(){
		return (Class<?>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
}
